package com.hjf.booking.security.config;

import com.alibaba.fastjson.JSON;
import com.hjf.booking.constants.BaseResponse;
import com.hjf.booking.security.authentication.SelfUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hjf
 * @date 2021-03-11 18:44
 */
@Component
public class JsonLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private SelfUserService selfUserService;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = selfUserService.getUserToken((String) authentication.getPrincipal());
        BaseResponse<String> successRes = BaseResponse.ok(token);
        response.getWriter().write(JSON.toJSONString(successRes));
    }
}
